package com.sikao.app.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.sikao.app.R;
import com.sikao.app.net.HttpApi;
import com.sikao.app.ui.base.BaseActivity;
import com.sikao.app.utils.ConstantClass;
import com.sikao.app.utils.Utils;

import dmax.dialog.SpotsDialog;

public class WebviewActivity extends BaseActivity implements View.OnClickListener {

	private   TextView titleTv;
	private ImageView backIv;
	private WebView webView;
	private String url;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_webview);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initData() {
		 url = getIntent().getStringExtra("url");
		 //url = "http://toutiao.com/a6329676642034041089/";
	}

	@Override
	protected void initView() {
		titleTv = (TextView) findViewById(R.id.title_middle_tv);
		backIv = (ImageView) findViewById(R.id.title_left_img);
		webView = (WebView) findViewById(R.id.webview);
	}

	@Override
	protected void initListener() {
		backIv.setOnClickListener(this);
	}

	@Override
	protected void init() {
	/*	if ((HttpApi.BANNERUTL + "api_1/teamBuy/teamlist").equals(url)){
			titleTv.setText("团购");
		}else{
			titleTv.setText("详情");
		}*/



		backIv.setVisibility(View.VISIBLE);



		webView.loadUrl(url);
		WebSettings webSettings = webView.getSettings();
		//支持js调用
		webSettings.setJavaScriptEnabled(true);
		//编码格式
		webSettings.setDefaultTextEncodingName("utf-8");
		//全屏，取消放大缩小功能
		//webSettings.setUseWideViewPort(true);
		//webSettings.setLoadWithOverviewMode(true);
		//设置本地调用对象及其接口   js 调用android.showToast("和共和国登陆 ");



		webView.addJavascriptInterface(new JavaScriptinterface(this), "android");
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				syncCookie(url, "PHPSESSID=" + HttpApi.sessionId);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
				//加载失败
				super.onReceivedError(view, request, error);

			}

		});
		webView.setWebChromeClient(new WebChromeClient() {
			//如果有标题会调用
			@Override
			public void onReceivedTitle(WebView view, String title) {
				//titleTv.setText(title);
			}

			//加载进度
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				//get the newProgress and refresh progress bar
			}
		});
	}

	/**
	 * 将cookie同步到WebView
	 * @param url WebView要加载的url
	 * @param cookie 要同步的cookie
	 * @return true 同步cookie成功，false同步cookie失败
	 * @Author JPH
	 */
	public   boolean syncCookie(String url,String cookie) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
			CookieSyncManager.createInstance(this);
		}
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.setCookie(url, cookie);//如果没有特殊需求，这里只需要将session id以"key=value"形式作为cookie即可
		String newCookie = cookieManager.getCookie(url);
		return TextUtils.isEmpty(newCookie)?false:true;
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.title_left_img:
				if (webView.canGoBack()) {
					webView.goBack();
				} else {
					finish();
				}
				break;
			default:
				break;
		}
	}

	@Override
	public void onBackPressed() {
		if (webView.canGoBack()) {
			webView.goBack();
		} else {
			finish();
		}
	}
	/*
		//支持javascript
		webSettings.setJavaScriptEnabled(true);
		// 设置可以支持缩放
		webSettings.setSupportZoom(true);
		// 设置出现缩放工具
		webSettings.setBuiltInZoomControls(true);
		//右下角缩放按钮隐藏
		webSettings.setDisplayZoomControls(false);
		//扩大比例的缩放
		webSettings.setUseWideViewPort(true);
		//滚动条显示与隐藏
		webView.setVerticalScrollBarEnabled(false);
		webView.setHorizontalScrollBarEnabled(false);
		//自适应屏幕
		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setLoadWithOverviewMode(true);
		//打开本包内asset目录下的index.html文件
		webView.loadUrl("file:///android_asset/index.html");
		//打开本地sd卡内的index.html文件
 		webView.loadUrl("content://com.android.htmlfileprovider/sdcard/index.html");
		//打开指定URL的html文件
		webView.loadUrl("http://wap.baidu.com");
		//优先使用缓存
		webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		//不使用缓存：
		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);*/


	String title = "";
	private SpotsDialog mDialog;
	Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message message) {

			titleTv.setText(title);
			return false;
		}
	});

	  public class JavaScriptinterface {
		  Context context;
		  public JavaScriptinterface(Context c) {
			  context= c;
		  }

		  /**
		   * 与js交互时用到的方法，在js里直接调用的
		   */

	   @JavascriptInterface
		  public void jsOption(String sat , final String mess) {
			  //Utils.showLog("=====jsOption web:"+mess);
		   Utils.showLog("=====jsOption titone :"+sat+" "+mess);
				switch (sat){
					case "toast":

						Utils.showToast(mess.toString());
						break;
					case "title":
						Utils.showLog("=====jsOption tit :"+sat+" "+mess);

						Message message = new Message();
						title = mess;
						message.arg1 = 1;
						handler.sendMessage(message);
					case "loading":
							if ("show".equals(mess)){
								if ( mDialog == null) {
									mDialog = new SpotsDialog(WebviewActivity.this, "拼命加载中...");
								}
								mDialog.show();
							}else if ("close".equals(mess)){
								if ( mDialog != null) {
									mDialog.cancel();
									mDialog = null;
								}
							}
						break;
					case "needLogin":

					//	if (ConstantClass.state == 0) {
							Intent intent = new Intent();
							intent.setClass(WebviewActivity.this, LoginActivity.class);
							startActivity(intent);
						//}
						break;
				}

			 //Toast.makeText(getApplication(), ssss, Toast.LENGTH_LONG).show();
			  //  finish();
		  }
	  }

	@Override
	protected void onResume() {
		super.onResume();
		syncCookie(url, "PHPSESSID=" + HttpApi.sessionId);
	}
}
